<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      title="分配数据管理"
      :width="'70%'"
      class="allocation-dialog"
      :close-on-click-modal="false"
    >
      <!-- 添加信息栏 -->
      <div v-if="!isInputMode" class="info-bar">
        <div class="info-item">
          <strong>类型：</strong>
          {{ objectTypeText }}
        </div>
        <div class="info-item">
          <strong>起始层：</strong>
          {{ startLayerText }}
        </div>
      </div>

      <!-- 查看模式 -->
      <div v-if="!isInputMode">
        <el-tabs v-model="activeLevel" class="level-tabs">
          <!-- 总用量 tab -->
          <el-tab-pane label="总用量" name="total">
            <el-table v-if="currentAllocation?.totalEnergy" :data="totalEnergyData" border class="allocation-table">
              <el-table-column prop="name" label="能源类型" />
              <el-table-column prop="value" label="用量" />
              <el-table-column prop="unit" label="单位" />
            </el-table>
            <el-empty v-else description="暂无数据" />
          </el-tab-pane>
          <el-tab-pane v-if="showTabs.organization" label="组织层" name="organization">
            <div class="table-wrapper">
              <el-table
                v-if="currentAllocation?.organizationLevel?.length"
                :data="currentAllocation.organizationLevel"
                border
                max-height="450"
                class="allocation-table"
              >
                <el-table-column prop="directEnergy" label="直接能耗" />
                <el-table-column prop="indirectEnergy" label="间接能耗" />
              </el-table>
              <el-empty v-else description="暂无数据" />
            </div>
          </el-tab-pane>
          <el-tab-pane v-if="showTabs.productionLine" label="产线层" name="productionLine">
            <el-table
              v-if="currentAllocation?.productionLineLevel?.length"
              :data="currentAllocation.productionLineLevel"
              border
              class="allocation-table"
            >
              <el-table-column prop="lineName" label="产线名称" />
              <el-table-column prop="productQuantity" label="产品产量" />
              <el-table-column prop="totalProductQuantity" label="所有产品产量" />
            </el-table>
            <el-empty v-else description="暂无数据" />
          </el-tab-pane>
          <el-tab-pane v-if="showTabs.equipment" label="设备层" name="equipment">
            <el-table
              v-if="currentAllocation?.equipmentLevel?.length"
              :data="currentAllocation.equipmentLevel"
              border
              class="allocation-table"
            >
              <el-table-column prop="equipmentName" label="设备名称" />
              <el-table-column prop="productionLine" label="所属产线" />
              <el-table-column prop="estimatedEnergy" label="设备预计能耗" />
              <el-table-column prop="totalEstimatedEnergy" label="所有设备预计能耗" />
            </el-table>
            <el-empty v-else description="暂无数据" />
          </el-tab-pane>
          <el-tab-pane v-if="showTabs.process" label="工序层" name="process">
            <el-table
              v-if="currentAllocation?.processLevel?.length"
              :data="currentAllocation.processLevel"
              border
              class="allocation-table"
            >
              <el-table-column prop="processName" label="特征工序" />
              <el-table-column prop="equipment" label="所属设备" />
              <el-table-column prop="processTime" label="特征工序加工时长" />
              <el-table-column prop="totalProcessTime" label="所有特征工序加工时长" />
              <el-table-column prop="processCount" label="特征工序加工次数" />
              <el-table-column prop="totalProcessCount" label="所有特征工序加工次数" />
            </el-table>
            <el-empty v-else description="暂无数据" />
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 录入模式 -->
      <allocation-input
        v-else
        :params="currentParams"
        :existing-data="currentAllocation"
        @close="handleInputClose"
        @save="handleInputSave"
      />

      <!-- 底部按钮区域 -->
      <template #footer>
        <span class="dialog-footer">
          <template v-if="!isInputMode">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleEnterInput">进入录入界面</el-button>
          </template>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed } from "vue";
import { allocationList } from "@/assets/mock/mockData";
import AllocationInput from "./allocationInput.vue";
import { ElMessageBox } from "element-plus";
import type { Allocation } from "@/api/interface";

interface DialogParams {
  projectId: string;
  typeId: string;
  id: string;
}

// 控制对话框显示
const dialogVisible = ref(false);
const isInputMode = ref(false);
const currentParams = ref<DialogParams>({
  projectId: "",
  typeId: "",
  id: ""
});

// 当前选中的层次
const activeLevel = ref("");

const currentAllocation = ref<Allocation.AllocationList | null>(null);

// 控制显示哪些 Tab
const showTabs = computed(() => {
  const startLayerId = currentAllocation.value?.startLayerId || "4";
  return {
    organization: ["4"].includes(startLayerId),
    productionLine: ["4", "3"].includes(startLayerId),
    equipment: ["4", "3", "2"].includes(startLayerId),
    process: true
  };
});

// 获取第一个可见的 tab
const getFirstVisibleTab = computed(() => {
  return "total"; // 默认显示总用量 tab
});

// 获取起始层次显示文本
const startLayerText = computed(() => {
  if (!currentAllocation.value) return "未定义";
  const startLayerId = currentAllocation.value.startLayerId;
  const layerMap: Record<string, string> = {
    "1": "工序层",
    "2": "设备层",
    "3": "产线层",
    "4": "组织层"
  };
  return layerMap[startLayerId as keyof typeof layerMap] || "未知层次";
});

// 获取对象类型显示文本
const objectTypeText = computed(() => {
  const typeId = currentParams.value.typeId;
  const typeMap: Record<string, string> = {
    "1": "物料",
    "2": "产品"
  };
  return typeMap[typeId] || "未知类型";
});

// 处理总用量数据
const totalEnergyData = computed(() => {
  const totalEnergy = currentAllocation.value?.totalEnergy;
  if (!totalEnergy) return [];

  return [
    { name: "水能", value: totalEnergy.waterUsage, unit: "m³" },
    { name: "天然气", value: totalEnergy.gasUsage, unit: "m³" },
    { name: "柴油", value: totalEnergy.oilUsage, unit: "L" },
    { name: "电能", value: totalEnergy.electricityUsage, unit: "kWh" }
  ];
});

// 进入录入界面
const handleEnterInput = async () => {
  if (currentAllocation.value) {
    try {
      await ElMessageBox.confirm("确认重新录入数据？当前数据会被覆盖。", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      });
      isInputMode.value = true;
    } catch {
      // 用户取消操作
    }
  } else {
    isInputMode.value = true;
  }
};

// 处理录入界面关闭
const handleInputClose = () => {
  isInputMode.value = false;
};

// 处理录入数据保存
const handleInputSave = (data: any) => {
  // 找到当前数据的索引
  const index = allocationList.value.findIndex(
    item =>
      item.projectId === currentParams.value.projectId &&
      item.objectId === currentParams.value.id &&
      item.objectType === currentParams.value.typeId
  );

  if (index !== -1) {
    // 更新已有数据
    allocationList.value[index] = data;
  } else {
    // 添加新数据
    allocationList.value.push(data);
  }

  // 只保存当前分配数据到 localStorage，使用唯一的 key
  const key = `currentAllocation_${currentParams.value.projectId}_${currentParams.value.typeId}`;
  try {
    localStorage.setItem(key, JSON.stringify(data));
  } catch (error) {
    console.error(`保存分配数据 ${key} 到 localStorage 失败:`, error);
  }

  // 更新当前显示的数据
  currentAllocation.value = { ...data } as Allocation.AllocationList;

  isInputMode.value = false;
  activeLevel.value = "total"; // 重置为总用量 tab
};

// 打开对话框方法
const openDialog = (params: DialogParams) => {
  currentParams.value = params;
  isInputMode.value = false;
  dialogVisible.value = true;
  activeLevel.value = getFirstVisibleTab.value;

  // 尝试从 localStorage 中查找数据
  const key = `currentAllocation_${params.projectId}_${params.typeId}`;
  const savedData = localStorage.getItem(key);

  if (savedData) {
    currentAllocation.value = JSON.parse(savedData) as Allocation.AllocationList;
    console.log("从 localStorage 加载数据:", currentAllocation.value);
  } else {
    const allocation = allocationList.value.find(
      item => item.projectId === params.projectId && item.objectId === params.id && item.objectType === params.typeId
    );

    if (allocation) {
      currentAllocation.value = { ...allocation } as Allocation.AllocationList;
      console.log("从 allocationList 加载数据:", currentAllocation.value);
    } else {
      console.warn("未找到匹配的分配数据");
    }
  }
};

// 暴露方法给父组件
defineExpose({
  openDialog
});
</script>

<style scoped>
.allocation-dialog :deep(.el-dialog) {
  position: relative !important;
  top: 10vh !important;
  display: flex;
  flex-direction: column;
  height: 600px !important;
}

/* 录入模式时调整位置 */
.allocation-dialog :deep(.el-dialog)[aria-label="分配数据管理"] {
  top: 5vh !important;
}
.allocation-dialog :deep(.el-dialog__header) {
  padding: 15px 20px;
  margin: 0;
  border-bottom: 1px solid #dcdfe6;
}
.allocation-dialog :deep(.el-dialog__footer) {
  padding: 15px 20px;
  border-top: 1px solid #dcdfe6;
}
.allocation-dialog :deep(.el-tabs) {
  display: flex;
  flex-direction: column;
}
.allocation-dialog :deep(.el-tabs__content) {
  flex: 1;
}
.allocation-dialog :deep(.el-tab-pane) {
  padding: 20px 0;
}
.allocation-table {
  width: 100%;
}
.level-tabs {
  margin-bottom: 20px;
}
.dialog-footer {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}
.info-bar {
  display: flex;
  justify-content: space-around;
  padding: 10px 0;
  margin: 20px 0;
  background-color: #f5f7fa;
  border-radius: 4px;
}
.info-item {
  font-size: 14px;
}
.info-item strong {
  margin-right: 8px;
  font-weight: bold;
  color: #333333;
}

/* 总用量表格样式优化 */
.allocation-table :deep(.el-table__header) {
  background-color: #f5f7fa;
}
.allocation-table :deep(.el-table__row) {
  height: 50px;
}
</style>
